package com.jt.service;

import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public String login(User user) {
        String password = user.getPassword();
        String md5Password= DigestUtils.md5DigestAsHex(password.getBytes());
        user.setPassword(md5Password);
        User userDB=userMapper.findUserByUP(user);
        if(userDB==null){
            return null;
        }
        String token = UUID.randomUUID().toString();
        return token;

    }

    /**
     * 分页查询SQl：
     * select * from user limit 起始位置，查询的条数
     * 第N页：
     * select * from user limit (n-1)*10,10
     * */
    @Override
    public PageResult list(PageResult pageResult) {
        //1.记录总记录数
        long total=userMapper.findTotal();
        //2.获取分页查询的结果
        int start=(pageResult.getPageNum()-1)*pageResult.getPageSize();//分页的起始位置
        int size=pageResult.getPageSize();//分页的条数
        String query=pageResult.getQuery();//用户查询的数据
        List<User> rows= userMapper.findUserList(start,size,query);
        return pageResult.setTotal(total).setRows(rows);
    }

    //新增用户，密码需要设置加密
    @Override
    public void saveUser(User user) {
        String password = user.getPassword();
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        user.setPassword(md5Password)
            .setStatus(true)
            .setCreated(new Date())
            .setUpdated(new Date());
        userMapper.saveUserById(user);

    }

    @Override
    public void status(User user) {
        user.setStatus(true)
            .setUpdated(new Date());
        userMapper.status(user);
    }

    @Override
    public User findUserById(Integer id) {
        return userMapper.findUserById(id);
    }

    @Override
    public void updateUser(User user) {
        user.setUpdated(new Date());
        userMapper.updateById(user);//MP写法
    }

    @Override
    public void deleteUserById(Integer id) {
        userMapper.deleteById(id);
    }
}
